<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成员管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
        <a class="navbar-brand" href="/dashboard">家族管理系统</a>
        <div class="collapse navbar-collapse">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/admin/members">成员管理</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/relations">关系管理</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">家族设置</a>
                </li>
            </ul>
            <form th:action="@{/logout}" method="post">
                <button type="submit" class="btn btn-outline-light">退出</button>
            </form>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="d-flex justify-content-between mb-4">
        <h2>家族成员管理</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMemberModal">
            添加成员
        </button>
    </div>

    <table class="table table-striped">
        <thead>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>头像</th>
            <th>联系方式</th>
            <th>个人简介</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="member : ${members}">
            <td th:text="${member.id}"></td>
            <td th:text="${member.name}"></td>
            <td>
                <img th:if="${member.avatarUrl}"
                     th:src="${member.avatarUrl}"
                     style="width: 50px; height: 50px; object-fit: cover; border-radius: 50%;">
            </td>
            <td th:text="${member.contactInfo}"></td>
            <td th:text="${#strings.abbreviate(member.personalDescription, 30)}"></td>
            <td>
                <button class="btn btn-sm btn-info">查看</button>
                <button class="btn btn-sm btn-warning edit-btn"
                        data-bs-toggle="modal"
                        data-bs-target="#editMemberModal"
                        th:attr="data-member-id=${member.id}">
                    编辑
                </button>
                <button class="btn btn-sm btn-danger delete-btn" th:data-member-id="${member.id}">
                    删除
                </button>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<!-- 添加成员模态框 -->
<div class="modal fade" id="addMemberModal" tabindex="-1" aria-labelledby="addMemberModalLabel" aria-hidden="true">
    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addMemberModalLabel">添加新成员</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="addMemberForm" th:action="@{/admin/members}" method="post"  enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="name" class="form-label">姓名</label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="contactInfo" class="form-label">联系方式</label>
                        <input type="text" class="form-control" id="contactInfo" name="contactInfo">
                    </div>
                    <div class="mb-3">
                        <label for="personalDescription" class="form-label">个人简介</label>
                        <textarea class="form-control" id="personalDescription" name="personalDescription" rows="3"></textarea>
                    </div>
                    <!-- 新增照片上传字段 -->
                    <div class="mb-3">
                        <label for="avatarUrl" class="form-label">成员照片</label>
                        <input type="file" class="form-control" id="avatarUrl" name="avatarUrl" accept="image/*">
                        <div class="form-text">支持JPG/PNG格式，大小不超过2MB</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑模态框（类似添加模态框） -->
<div class="modal fade" id="editMemberModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑成员</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form th:action="@{/admin/members/{id}/edit(id=${member.id})}" method="post"   enctype="multipart/form-data">
                <input type="hidden" name="_method" value="put">
                <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">姓名</label>
                        <input type="text" class="form-control" name="name" th:value="${member.name}">
                    </div>

                    <!-- 头像预览 -->
                    <div class="mb-3 text-center">
                        <img id="editAvatarPreview"
                             style="width: 100px; height: 100px; object-fit: cover; border-radius: 50%; margin-bottom: 10px;">
                        <input type="file" class="form-control" name="avatarUrl" accept="image/*">
                    </div>

                    <div class="mb-3">
                        <label for="contactInfo2" class="form-label">联系方式</label>
                        <input type="text" class="form-control" id="contactInfo2" name="contactInfo" th:value="${member.contactInfo}">
                    </div>

                    <div class="mb-3">
                        <label for="personalDescription2" class="form-label">个人简介</label>
                        <textarea class="form-control" id="personalDescription2" name="personalDescription" rows="3" th:value="${member.personalDescription}"></textarea>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script th:inline="javascript">
    // 处理添加成员表单提交
    document.getElementById('addMemberForm').addEventListener('submit', function(e) {
        e.preventDefault();

        // 创建FormData对象（自动处理文件字段）
        const formData = new FormData(this);

        fetch(this.action, {
            method: 'POST',
            body: formData,  // 直接传递FormData对象
            // 不要手动设置Content-Type，浏览器会自动添加正确的boundary
        })
            .then(response => {
                if (response.ok) {
                    bootstrap.Modal.getInstance(document.getElementById('addMemberModal')).hide();
                    location.reload();
                } else {
                    alert('保存失败: ' + response.statusText);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误: ' + error.message);
            });
    });

    // 事件委托方式
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('delete-btn')) {
            const memberId = e.target.getAttribute('data-member-id');
            if (confirm('确定删除ID为 ' + memberId + ' 的成员吗？')) {
                fetch(`/admin/members/${memberId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('[name="_csrf"]').value
                    }
                }).then(response => location.reload());
            }
        }
    });


    const editModal = document.getElementById('editMemberModal');
    if (editModal) {
        editModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const memberId = button.getAttribute('data-member-id');

            fetch(`/admin/members/${memberId}`)
                .then(response => response.json())
                .then(data => {
                    const form = document.getElementById('editMemberForm');

                    // 填充基本字段
                    form.querySelector('input[name="name"]').value = data.name;
                    // 其他字段...

                    // 处理头像
                    const preview = document.getElementById('editAvatarPreview');
                    if (data.avatarUrl) {
                        preview.src = data.avatarUrl;
                        preview.style.display = 'block';
                    } else {
                        preview.style.display = 'none';
                    }

                    // 更新表单action（确保使用当前memberId）
                    form.action = `/admin/members/${memberId}`;
                });
        });

        // 实时预览新选择的头像
        editModal.querySelector('input[name="avatarUrl"]').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const preview = document.getElementById('editAvatarPreview');
                    preview.src = event.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            }
        });
    }

    document.getElementById('editMemberForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const memberId = this.action.split('/').pop();

        fetch(this.action, {
            method: 'POST', // 注意：实际使用PUT但需要通过_method覆盖
            body: formData,
            headers: {
                'X-CSRF-TOKEN': document.querySelector('[name="_csrf"]').value
            }
        })
            .then(response => {
                if (response.ok) {
                    bootstrap.Modal.getInstance(editModal).hide();
                    location.reload();
                } else {
                    alert('更新失败');
                }
            });
    });
</script>
</body>
</html>